package com.pet.inter.servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.pet.dao.OperateDb;
import com.pet.inter.bean.QueryTopicBacksInfoBean;
import com.pet.inter.bean.QueryTopicsInfoBean;
import com.pet.inter.bean.ResultBean;
import com.pet.inter.bean.TopicBackBean;
import com.pet.inter.bean.TopicBean;
import com.pet.inter.bean.UserInfoBean;
import com.pet.util.ConstantsUtil;
import com.pet.util.CreateSequencesUtil;
import com.pet.util.JsonUtil;
import com.pet.util.ResourceUtil;
import com.pet.util.UploadUtil;

public class InterFaceServlet extends HttpServlet {
	private static final long serialVersionUID = 138932047271970321L;
	private OperateDb db;
	private static final Log log = LogFactory.getLog(InterFaceServlet.class);
	@Override
	public void init(ServletConfig config) throws ServletException {
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
		this.db = (OperateDb)wac.getBean("db");
		ResourceUtil.initResourceMap(config.getServletContext().getRealPath(File.separator) + "WEB-INF/classes/com/pet/properties");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		log.info("requestType = " + req.getParameter("requestType"));
		req.setCharacterEncoding("UTF-8");
		// 登陆
		if(ConstantsUtil.REQUESTTYPE_LOGIN.equals(req.getParameter("requestType"))){
			Map<String, String> paramMap = new HashMap<String, String>(); 
			paramMap.put("userId", req.getParameter("userId"));
			paramMap.put("pwd", req.getParameter("pwd"));
			Map map = db.queryUserInfo(paramMap);
			ResultBean rb = new ResultBean();
			if(map != null && map.keySet().size() > 0){
				rb.setResCode(ConstantsUtil.SUCCESS);
				rb.setDesc(ConstantsUtil.SUCCESS_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_LOGIN);
			} else {
				rb.setResCode(ConstantsUtil.FAILED);
				rb.setDesc(ConstantsUtil.FAILED_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_LOGIN);
			}
			log.info("returnResult = " + JsonUtil.getJsonString4JavaPOJO(rb));
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write(JsonUtil.getJsonString4JavaPOJO(rb));
		} 
		// 注册
		else if(ConstantsUtil.REQUESTTYPE_REGISTER.equals(req.getParameter("requestType"))){
			Map<String, String> paramMap = new HashMap<String, String>(); 
			paramMap.put("userId", req.getParameter("userId"));
			paramMap.put("userName", req.getParameter("userName"));
			paramMap.put("pwd", req.getParameter("pwd"));
			int rs = db.insertUserInfo(paramMap);
			ResultBean rb = new ResultBean();
			if(rs > 0){
				rb.setResCode(ConstantsUtil.SUCCESS);
				rb.setDesc(ConstantsUtil.SUCCESS_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_REGISTER);
			} else {
				rb.setResCode(ConstantsUtil.FAILED);
				rb.setDesc(ConstantsUtil.FAILED_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_REGISTER);
			}
			log.info("returnResult = " + JsonUtil.getJsonString4JavaPOJO(rb) );
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write(JsonUtil.getJsonString4JavaPOJO(rb));
		} 
		// 查询用户信息
		else if(ConstantsUtil.REQUESTTYPE_USERINFO.equals(req.getParameter("requestType"))){
			Map<String, String> paramMap = new HashMap<String, String>(); 
			paramMap.put("userId", req.getParameter("userId"));
			UserInfoBean bean = db.queryUserInfos(paramMap);
			ResultBean rb = new ResultBean();
			if(bean != null){
				rb.setResCode(ConstantsUtil.SUCCESS);
				rb.setDesc(ConstantsUtil.SUCCESS_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_USERINFO);
				rb.setUserInfo(bean);
			} else {
				rb.setResCode(ConstantsUtil.FAILED);
				rb.setDesc(ConstantsUtil.FAILED_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_USERINFO);
			}
			log.info("returnResult = " + JsonUtil.getJsonString4JavaPOJO(rb));
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write(JsonUtil.getJsonString4JavaPOJO(rb));
		} 
		// 修改用户信息
		else if(ConstantsUtil.REQUESTTYPE_MOTIFYUSER.equals(req.getParameter("requestType"))){
			Map<String, String> paramMap = new HashMap<String, String>(); 
			paramMap.put("userId", req.getParameter("userId"));
			paramMap.put("nickname", req.getParameter("nickname"));
			paramMap.put("qq", req.getParameter("qq"));
			paramMap.put("mail", req.getParameter("mail"));
			int rs = db.updatetUserInfo(paramMap);
			log.info("修改用户信息 userId = " + req.getParameter("userId") + " rs = " + rs );
			ResultBean rb = new ResultBean();
			if(rs > 0){
				rb.setResCode(ConstantsUtil.SUCCESS);
				rb.setDesc(ConstantsUtil.SUCCESS_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_MOTIFYUSER);
			} else {
				rb.setResCode(ConstantsUtil.FAILED);
				rb.setDesc(ConstantsUtil.FAILED_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_MOTIFYUSER);
			}
			log.info("returnResult = " + JsonUtil.getJsonString4JavaPOJO(rb) );
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write(JsonUtil.getJsonString4JavaPOJO(rb));
		}
		// 发帖，包括上传宠物信息
		else if(ConstantsUtil.REQUESTTYPE_CREATETOPIC.equals(req.getParameter("requestType"))){
			Map<String, String> reqMap = null;
			boolean isHaveData = ServletFileUpload.isMultipartContent(req);
			String imagPath = "";
	        if (isHaveData) {
	            FileItemFactory factory = new DiskFileItemFactory();
	            ServletFileUpload upload = new ServletFileUpload(factory);
	            try {
	                List items = upload.parseRequest(req);
	                Iterator iter = items.iterator();
	                reqMap = new HashMap<String, String>();
	                while (iter.hasNext()) {
	                    FileItem item = (FileItem) iter.next();
	                    if (item.isFormField()) {
	                        // 普通文本信息处理
	                        String paramName = item.getFieldName();
	                        String paramValue = item.getString();
	                        log.info(paramName + ":" + paramValue);
	                        reqMap.put(paramName, paramValue);
	                    }else {
	                        String fileName=item.getName();// 获得文件名，包括路径
	                		if(fileName != null && !"".equals(fileName)){
	                			String extend = ".jpg";
	                			if(item.getName().indexOf(".") != -1){
	                				extend = item.getName().substring(item.getName().indexOf("."));
	                			}
	                			String imgName = CreateSequencesUtil.createID("IM") + extend;
	                			File savedFile = new File(UploadUtil.getImagePath(req), imgName);
	                			try {
									item.write(savedFile);
								} catch (Exception e) {
									e.printStackTrace();
								}
	                			imagPath = "img/" + imgName;
	                		}
	                    }
	                }
	            } catch (FileUploadException e) {
	                e.printStackTrace();
	            }
	        }
	        int rs = 0;
			if(reqMap != null && reqMap.keySet().size() > 0){
				if(imagPath != null && !"".equals(imagPath)){
					log.info("上传文件成功，文件保存地址：" + imagPath);
					Map<String, String> paramMap = new HashMap<String, String>(); 
					paramMap.put("topic_id", CreateSequencesUtil.createID("TO"));
					paramMap.put("user_id", reqMap.get("userId"));
					paramMap.put("title", reqMap.get("title"));
					paramMap.put("content", reqMap.get("content"));
					paramMap.put("img_path", ResourceUtil.getResourceMap().get("systemUrl") + imagPath);
					rs = db.insertTopicInfo(paramMap);
				} else {
					log.info("上传文件保存失败！");
				}
			}
			ResultBean rb = new ResultBean();
			if(rs > 0){
				rb.setResCode(ConstantsUtil.SUCCESS);
				rb.setDesc(ConstantsUtil.SUCCESS_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_CREATETOPIC);
			} else {
				rb.setResCode(ConstantsUtil.FAILED);
				rb.setDesc(ConstantsUtil.FAILED_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_CREATETOPIC);
			}
			log.info("returnResult = " + JsonUtil.getJsonString4JavaPOJO(rb) );
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write(JsonUtil.getJsonString4JavaPOJO(rb));
		}
		
		// 查询帖子
		else if(ConstantsUtil.REQUESTTYPE_QUERYTOPICS.equals(req.getParameter("requestType"))){
			String userId = req.getParameter("userId");
			QueryTopicsInfoBean returnBean = new QueryTopicsInfoBean();
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("userId", req.getParameter("userId"));
			List<TopicBean> list = db.queryTopicsInfos(paramMap);
			returnBean.setResCode(ConstantsUtil.SUCCESS);
			returnBean.setDesc(ConstantsUtil.SUCCESS_DESC);
			returnBean.setList(list);
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write(JsonUtil.getJsonString4JavaPOJO(returnBean));
		}
		
		// 回帖
		else if(ConstantsUtil.REQUESTTYPE_CREATETOPICBACK.equals(req.getParameter("requestType"))){
			Map<String, String> paramMap = new HashMap<String, String>(); 
			paramMap.put("topic_back_id", CreateSequencesUtil.createID("TB"));
			paramMap.put("topic_id", req.getParameter("topic_id"));
			paramMap.put("user_id", req.getParameter("userId"));
			paramMap.put("content", req.getParameter("content"));
			int rs = db.insertTopicBackInfo(paramMap);
			ResultBean rb = new ResultBean();
			if(rs > 0){
				rb.setResCode(ConstantsUtil.SUCCESS);
				rb.setDesc(ConstantsUtil.SUCCESS_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_CREATETOPICBACK);
			} else {
				rb.setResCode(ConstantsUtil.FAILED);
				rb.setDesc(ConstantsUtil.FAILED_DESC);
				rb.setRequestType(ConstantsUtil.REQUESTTYPE_CREATETOPICBACK);
			}
			log.info("returnResult = " + JsonUtil.getJsonString4JavaPOJO(rb) );
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write(JsonUtil.getJsonString4JavaPOJO(rb));
		}
		
		// 查询回复帖子
		else if(ConstantsUtil.REQUESTTYPE_QUERYTOPICBACK.equals(req.getParameter("requestType"))){
			String topic_id = req.getParameter("topic_id");
			QueryTopicBacksInfoBean returnBean = new QueryTopicBacksInfoBean();
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("topic_id", topic_id);
			List<TopicBackBean> list = db.queryTopicBacksInfos(paramMap);
			returnBean.setResCode(ConstantsUtil.SUCCESS);
			returnBean.setDesc(ConstantsUtil.SUCCESS_DESC);
			returnBean.setList(list);
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write(JsonUtil.getJsonString4JavaPOJO(returnBean));
		}
	}
}
